package com.banciyuan.bcywebview.biz.main.discover.topwork;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.fragment.BaseLazyContainerFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.timelinedatacenter.DetailDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshBase;
import com.banciyuan.bcywebview.base.view.pulltorefresh.PullToRefreshListView;
import com.banciyuan.bcywebview.biz.novel.NovelAdapter;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Novel;
import de.greenrobot.daoexample.model.TagDetail;


public class NovelTopWorkFragment extends BaseLazyContainerFragment {
    private PullToRefreshListView mRefresh;
    private ListView mListView;
    protected ProgressbarHelper mProgressbarHelper;
    private List<Novel> mNovelList = new ArrayList<>();
    private NovelAdapter adapter;
    private String mRankType;
    private int page = 1;
    private String date;
    private boolean loading = false;
    private boolean isEnd = false;
    private String url;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.top_fragment_layout, container, false);
        initArgs();
        initProgressbar(rootView);
        initUi(rootView);
        initAction();
        return rootView;
    }

    @Override
    protected void initArgs() {
        Bundle arguments = getArguments();
        mRankType = arguments.getString(gotoUtil.INTENT_VALUE_ONE);
        date = arguments.getString(gotoUtil.INTENT_VALUE_THREE);
        url = HttpUtils.BASE_URL + NovelApi.getNovelTopList();

    }

    @Override
    public void fetchData() {
        loading = false;
        isEnd = false;
        page = 1;
        initData();
    }

    @Override
    protected void initProgressbar(View rootview) {
        View mProgressbarView = rootview.findViewById(R.id.base_progressbar);
        mProgressbarHelper = new ProgressbarHelper(mProgressbarView);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                if (!loading) {
                    loading = true;
                    mProgressbarHelper.onLoading();
                    isEnd = false;
                    page = 1;
                    initData();
                }
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        mRefresh = (PullToRefreshListView) rootview.findViewById(R.id.top_refresh_lv);
        mListView = mRefresh.getRefreshableView();
        View footer = new View(getActivity());
        ListView.LayoutParams ll = new ListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, UIUtils.dip2px(36, getActivity()));
        footer.setLayoutParams(ll);
        mListView.addFooterView(footer);
    }

    @Override
    protected void initAction() {
        mRefresh.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loading = false;
                isEnd = false;
                page = 1;
                initData();
            }
        });
        mRefresh.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                if (!loading && !isEnd) {
                    loading = true;
                    page++;
                    initData();
                }
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                int index = i - 1;
                if (index < 0 || index > mNovelList.size()) return;
                Novel novel = mNovelList.get(index);
                if (null != novel) {
                    DetailDataHelper.gotoWriterDetail(getActivity(), novel.getRp_id(), novel.getWp_id(), false);
                }
            }
        });
    }

    @Override
    protected void initData() {
        loading = true;
        List<BcyPair> paramsList = new ArrayList<>();
        if (!TextUtils.isEmpty(mRankType)) {
            paramsList.add(new BcyPair(HttpUtils.TYPE, mRankType));
        }
        if (!TextUtils.isEmpty(date)) {
            paramsList.add(new BcyPair("date", date));
        }
        paramsList.add(new BcyPair(HttpUtils.PAGE, page + ""));
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                        JSONObject jsonObject = new JSONObject(response);
                        List<Novel> tempNovelList = new Gson().fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<Novel>>() {
                        }.getType());
                        for (Novel novel : tempNovelList) {
                            if (!TextUtils.isEmpty(novel.getWork()))
                                novel.getPost_tags().add(0, new TagDetail(novel.getWid(), novel.getWork(), novel.getWork()));
                        }
                        processData(tempNovelList);
                        onSuccess();
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
                    }
                } catch (Exception e) {
                    onError();
                    BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                onError();
                BaseObserver.getInstance().notifyWatchers(BaseObserver.RANK_REFREASH);
            }
        };
        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), map);
        StringRequestParam getUserdataRequest = new StringRequestParam(Request.Method.POST, url, map, onSuccess, errorProxy);
        VolleyQueue.getRquest(getActivity()).add(getUserdataRequest);
    }

    private void onSuccess() {
        mProgressbarHelper.onSuccess();
        mRefresh.onRefreshComplete();
        loading = false;
    }

    private void onError() {
        loading = false;
        mProgressbarHelper.onFailed();
        mRefresh.onRefreshComplete();
    }

    private void processData(List<Novel> novelList) {
        if (novelList.isEmpty())
            isEnd = true;
        if (page == 1)
            mNovelList.clear();
        mNovelList.addAll(novelList);
        if (null == adapter) {
            adapter = new NovelAdapter(getActivity(), mNovelList);
            mListView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        mProgressbarHelper.onSuccess();
    }

    public void setDate(String date) {
        this.date = date;
    }

    public void resetUi() {
        mProgressbarHelper.onLoading();
    }

    @Override
    public void selfUpdateData() {
        if (isVisibleToUser) {
            mRefresh.setRefreshing();
        }
    }
}
